﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System.Reflection;
using System.Text;

namespace ServiceCore.Utility.Extension
{
    public static class UtilityJson
    {
        #region 将字符串序列化成一个对象

        /// <summary>
        /// 将字符串序列化成一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T ToObject<T>(this string str) where T : class
        {
            var serializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
            var serializer = Newtonsoft.Json.JsonSerializer.Create(serializerSettings);
            using (StringReader reader = new StringReader(str))
            {
                using (var jsonReader = new Newtonsoft.Json.JsonTextReader(reader))
                {
                    return serializer.Deserialize<T>(jsonReader);
                }
            }
        }

        #endregion 将字符串序列化成一个对象

        #region 将字符串序列化成一个对象

        /// <summary>
        /// 将字符串序列化成一个对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T ToObjectIgnoreMetaData<T>(this string str) where T : class
        {
            var serializerSettings = new Newtonsoft.Json.JsonSerializerSettings();
            serializerSettings.MetadataPropertyHandling = MetadataPropertyHandling.Ignore;
            var serializer = Newtonsoft.Json.JsonSerializer.Create(serializerSettings);
            using (StringReader reader = new StringReader(str))
            {
                using (var jsonReader = new Newtonsoft.Json.JsonTextReader(reader))
                {
                    return serializer.Deserialize<T>(jsonReader);
                }
            }
        }
        #endregion 将字符串序列化成一个对象

        #region 将一个对象序列化成字符串

        /// <summary>
        /// 将一个对象序列化成字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        public static string ToJson<T>(this T t, bool IsIntend = false) where T : class
        {
            var serializerSettings = new JsonSerializerSettings();
            if (IsIntend == false)
                serializerSettings.Formatting = Newtonsoft.Json.Formatting.None;
            else
                serializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;

            var timeFormat = new IsoDateTimeConverter();
            timeFormat.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
            serializerSettings.Converters.Add(timeFormat);
            var serializer = Newtonsoft.Json.JsonSerializer.Create(serializerSettings);
            StringBuilder builder = new StringBuilder();
            using (StringWriter writer = new StringWriter(builder))
            {
                serializer.Serialize(writer, t);
            }
            return builder.ToString();
            //return builder.ToString();
            //var op = new Options(dateFormat: DateTimeFormat.ISO8601, includeInherited:true);
            //var result = JSON.Serialize(t, op);
            //return result;
        }

        /// <summary>
        /// 对象转JSON
        /// </summary>
        /// <param name="o">对象</param>
        /// <returns>JSON字符串</returns>
        public static string ToJsonStr(this object o)
        {
            if (o == null)
            {
                return null;
            }
            return JsonConvert.SerializeObject(o);
        }

        #endregion 将一个对象序列化成字符串

        
        #region 把缩短的json改成正常格式的json

        /// <summary>
        /// 把缩短的json改成正常格式的json
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FormatJsonNormal(this string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;
            //格式化json字符串
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            TextReader tr = new StringReader(str);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Newtonsoft.Json.Formatting.Indented,
                    Indentation = 4,
                    IndentChar = ' '
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }

        #endregion 把缩短的json改成正常格式的json

        #region 判断json是否正确

        /// <summary>
        /// 判断json是否正确
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string JsonVerify(this string str, string noticemsg)
        {
            if (string.IsNullOrEmpty(str))
                return "";
            try
            {
                if (JToken.Parse(str) != null)
                    return "";
                else
                    return noticemsg;
            }
            catch
            {
                return noticemsg;
            }
        }

        #endregion 判断json是否正确

        #region 把json转成动态类

        /// <summary>
        /// 把json转成动态类
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static dynamic JsonToDynamic(this string json)
        {
            return JsonConvert.DeserializeObject<dynamic>(json);
        }

        #endregion 把json转成动态类

        #region 把json转成动态类

        /// <summary>
        /// 把json转成动态类
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static void JsonToDynamicClass(this string json, object obj)
        {
            if (string.IsNullOrEmpty(json) || obj == null)
                return;
            JObject jsonObj = JsonConvert.DeserializeObject(json) as JObject;
            var dic = new Dictionary<string, string>();
            foreach (var p in jsonObj.Properties().ToArray())
            {
                dic.Add(p.Name, jsonObj[p.Name].Value<string>());
            }

            var pis = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);//获得对象的所有public属性
            foreach (var pi in pis)//针对每一个属性进行循环
            {
                Type proertyType = pi.PropertyType; //获得对象属性的类型
                if (dic.ContainsKey(pi.Name))
                    pi.SetValue(obj, Convert.ChangeType(dic[pi.Name], proertyType), null);
            }
        }

        #endregion 把json转成动态类

        #region 把json格式字符串转换无格式的json字符串

        /// <summary>
        /// 把json格式字符串转换无格式的json字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string JsonFormatNone(this string str)
        {
            //格式化json字符串
            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            TextReader tr = new StringReader(str);
            JsonTextReader jtr = new JsonTextReader(tr);
            object obj = serializer.Deserialize(jtr);
            if (obj != null)
            {
                StringWriter textWriter = new StringWriter();
                JsonTextWriter jsonWriter = new JsonTextWriter(textWriter)
                {
                    Formatting = Newtonsoft.Json.Formatting.None,
                };
                serializer.Serialize(jsonWriter, obj);
                return textWriter.ToString();
            }
            else
            {
                return str;
            }
        }

        #endregion 把json格式字符串转换无格式的json字符串
    }
}
